package com.medusa.aps.business.common.security.resource.tool;

import com.alibaba.fastjson2.JSON;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;

import java.io.IOException;
import java.util.List;

/**
 * 响应处理 工具类
 *
 * @author 张治保
 * date 2022/2/28
 */
@Component
public class ResponseUtil {

    private static List<HttpMessageConverter<?>> messageConverters;

    public ResponseUtil(RequestMappingHandlerAdapter requestMappingHandlerAdapter) {
        ResponseUtil.messageConverters = requestMappingHandlerAdapter.getMessageConverters();
    }

    /**
     * 响应数据
     *
     * @param response 响应
     * @throws IOException IO 异常
     */
    @SuppressWarnings({"unchecked", "rawtypes"})
    public static void response(HttpServletResponse response, Object value) throws IOException {
        MediaType selectedMediaType = MediaType.APPLICATION_JSON;
        Class<?> valueType = value.getClass();
        //优先尝试使用 HttpMessageConverter
        for (HttpMessageConverter<?> converter : messageConverters) {
            if (converter.canWrite(valueType, selectedMediaType)) {
                ((HttpMessageConverter) converter).write(value, selectedMediaType, new ServletServerHttpResponse(response));
                return;
            }
        }
        //尝试失败 使用默认方式
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.getWriter().println(JSON.toJSONString(value));
        response.setStatus(HttpServletResponse.SC_OK);
        response.flushBuffer();
    }


}
